﻿<?php
/*
 *根据腾讯IP分享计划的地址获取IP所在地，比较精确
 */
   $queryIP = GetIP();
    $url = 'http://ip.qq.com/cgi-bin/searchip?searchip1='.$queryIP;
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_ENCODING ,'gb2312');
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
    $result = curl_exec($ch);
    $result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换，否则乱码
    curl_close($ch);
	$file = fopen("c:\\test.txt","w+");
	fwrite($file,$result);
    preg_match("@<span>(.*)</span></p>@iU",$result,$ipArray);
    $loc = $ipArray[1];
    echo $loc;

/*
 *根据新浪IP查询接口获取IP所在地
 */
function getIPLoc_sina($queryIP){
    $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$queryIP;
	$ch = curl_init($url);
	//curl_setopt($ch,CURLOPT_ENCODING ,'utf8');
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
    $location = curl_exec($ch);
	$location = json_decode($location);
	curl_close($ch);
	
	$loc = "";
	if($location===FALSE) return "";
	if (empty($location->desc)) {
		$loc = $location->province.$location->city.$location->district.$location->isp;
	}else{
		$loc = $location->desc;
	}
	return $loc;
}

function GetIP()
{
//REMOTE_ADDR 是你的客户端跟服务器“握手”时候的IP。如果使用代理，REMOTE_ADDR将显示代理服务器的IP。
//HTTP_CLIENT_IP 是代理服务器设置发送的HTTP头，代表你的客户端的真实IP。当然，人家可以选择设置与否以及设置成什么样。
//HTTP_X_FORWARDED_FOR 是用户到达最终访问地时经过的路径访问点（包括自身和使用的多层代理）的IP列表。依然取决于代理的设置，可以伪造
	if(!empty($_SERVER["HTTP_CLIENT_IP"])){
		$cip = $_SERVER["HTTP_CLIENT_IP"];
	}else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
		$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	}else if(!empty($_SERVER["REMOTE_ADDR"])){
		$cip = $_SERVER["REMOTE_ADDR"];
	}else{
		$cip = '';
	}
	preg_match("/[\d\.]{7,15}/", $cip, $cips);
	$cip = isset($cips[0]) ? $cips[0] : 'unknown';
	unset($cips);
	return $cip;
}
?>
